/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        //边界检查 没有结点和只有一个结点的情况
        if (head == null || head.next == null) {
            return head;
        }
        ListNode workNode = head;
        //一次遍历计算链表长度，并将其改编为首尾相连的链表
        int length = 0;
        while (true) {
            length++;
            if (workNode.next == null) {
                workNode.next = head;
                break;
            }
            workNode = workNode.next;
        }
        workNode = head;    //工作指针重新指向head，开始新一轮工作
        int move = 0;   //定义偏移量
        if (k >= length) {
            move = k % length;  //偏移量其实就是 k % length，这一点非常重要
        } else {
            move = k;
        }

        //计算返回。
        //偏移量是1，那么就从最尾部开始返回，偏移量是2，就从最尾部-1开始返回 ...... 以此类推
        int times = length-move;
        for (int i = 0; i < times; i++) {
            workNode = workNode.next;
        }
        ListNode result = workNode;
        workNode = result;    //工作指针指向结果结点，开始新一轮工作
        //花费On的复杂度将其首尾链接打断
        for (int i = 0; i < length-1; i++) {
            workNode = workNode.next;
        }
        workNode.next = null;   //打断
        return result;

    }
}